package danran.regular;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @Classname StringMultiply
 * @Description TODO
 * @Date 2021/11/9 21:07
 * @Created by ASUS
 */
public class StringMultiply {
    public static String multiply(String a, String b) {
        List<String> tmp = new ArrayList<>(b.length());
        StringBuilder builder = new StringBuilder();
        int maxL = 0;
        for (int i = 0; i < b.length(); i++) {
            builder.delete(0, builder.length());// clear the builder.
            int idx = b.length() - 1 - i;
            builder.append("0".repeat(Math.max(0, idx)));// 添加0
            int x = b.charAt(i) - '0';// 乘数
            int y = 0;// 乘数
            int c = 0;// 进位
            int m = 0;// 中间乘积结果
            for (int j = a.length() - 1; j >= 0; j--) {
                y = a.charAt(j) - '0';
                m = x * y + c;
                c = m / 10;
                builder.append(m % 10);
            }
            if (c != 0) builder.append(c);
            tmp.add(builder.toString());
            maxL = Math.max(maxL, builder.length());
        }
        for (int i = 0; i < tmp.size(); i++) {
            builder = new StringBuilder(tmp.get(i));
            builder.append("0".repeat(maxL - builder.length()));
            tmp.set(i, builder.reverse().toString());
        }
        // add function
//        System.out.println(tmp);
        builder.delete(0, builder.length());
        int c = 0;
        for (int i = maxL - 1; i >= 0; i--) {
            int sum = getIndexSumOf(i, tmp) + c;
            c = sum / 10;
            builder.append(sum % 10);
        }
        if (c != 0) builder.append(c);
        int f = 0;
        for (int i = 0; i < builder.length(); i++) {
            if (builder.charAt(i) != '0') {
                f = 1;
                break;
            }
        }
        return f == 1 ? builder.reverse().toString() : "0";
    }

    private static int getIndexSumOf(int idx, List<String> array) {
        int ans = 0;
        for (String s : array) ans += s.charAt(idx) - '0';
        return ans;
    }

    public static void main(String[] args) {
        Random random = new Random();
        int cnt = 0;
        for (int i = 0; i < 10; i++) {
            int a = random.nextInt(1000);
            int b = random.nextInt(100000);
            if (String.valueOf(a * b).equals(multiply(String.valueOf(a), String.valueOf(b)))) cnt++;
        }
        System.out.println(cnt);
    }
}
